package com.winning.bi.jdbc;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;
import org.quartz.SchedulerException;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.winning.bi.jdbc.dao.Dao;

@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class SqlJob implements Job {

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		ClassPathXmlApplicationContext ac = (ClassPathXmlApplicationContext) context.getMergedJobDataMap().get("ac");
		Dao dao = (Dao) ac.getBean("daoTask");
		List<ScheduleJob> jobs = new ArrayList<ScheduleJob>();
		List<Map<String, Object>> list = dao.taskInfo();
		List<String> lists = new ArrayList<String>();
		// String [] strings = null;
		try {
			jobs = QuartzUtils.getAllJob(ac);

			for (int i = 0; i < jobs.size(); i++) {
				lists.add(jobs.get(i).getJobName());
			}
		} catch (SchedulerException e1) {

			e1.printStackTrace();
		}

		// log.info(JSON.toJSONString(list));
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map = list.get(i);
			if (!lists.contains(map.get("jobid").toString())) {
				ScheduleJob job = new ScheduleJob();

				job.setCronExpression(map.get("cron").toString());// Cron表达式

				job.setJobStatus(ScheduleJob.STATUS_RUNNING);
				job.setIsConcurrent(ScheduleJob.CONCURRENT_NOT);// 是否允许并行运行

				job.setJobName(map.get("jobid").toString());// job名称
				job.setMap(map);

				job.setErrorStatus(ScheduleJob.ERROR_NO_STOP);// 任务出现错误后是否停止

				job.setMisfireStatus(ScheduleJob.MISFIRE_STATUS_DO_NOTHING);// 调度策略详见注释
				try {

					QuartzUtils.addJob(job, ac);
				} catch (SchedulerException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

}
